#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2009 Denis Mingulov
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


import os
import wsgiref.handlers

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.1')

from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api import memcache

from engine import modules
from engine import persons

class MainHandler(webapp.RequestHandler):
    def get_page_data(self, strType, allowEdit, allowBuy, showAll):
        hashString = "moduleTypeList%s_edit%s_buy%s_all%s" % (strType, allowEdit, allowBuy, showAll)
        data = memcache.get( hashString )
        if data is not None:
            return data
        else:
            strType = '' + strType + 'Type';
            if hasattr(modules, strType):
                type = eval('modules.' + strType)
                if not issubclass(type, modules.ModuleType):
                    type = None
            else:
                type = None
 
            moduletypelist = []

            if type:
                if showAll:
                    moduletypelist = type.all()
                else:
                    query = type.gql("WHERE status in (1,2) ORDER BY class,__key__")
                    moduletypelist = query.fetch(1000)
                    print len(moduletypelist)

            menulist = ['Корабельные модули', ['<a href="?type=Weapon">Оружие</a>', ['<a href="?type=LaserWeapon">Лазерное</a>', '<a href="?type=PlasmaWeapon">Плазменное</a>', '<a href="?type=RocketWeapon">Ракетное</a>', '<a href="?type=MineWeapon">Минное</a>', '<a href="?type=EnergyWeapon">Энергетическое</a>', '<a href="?type=GravityWeapon">Гравитационное</a>'], '<a href="?type=Radar">Радары</a>', ['<a href="?type=BattleRadar">Боевые</a>', '<a href="?type=JammerRadar">Помехи</a>', '<a href="?type=NavigationRadar">Навигационные</a>', '<a href="?type=LongRangeRadar">Сверхдальние</a>'], '<a href="?type=PowerUnit">Энергоустановки</a>', '<a href="?type=Computer">Компьютеры</a>', ['<a href="?type=BattleComputer">Боевые</a>', '<a href="?type=NavigationComputer">Навигационные</a>'], '<a href="?type=Compartment">Жилые отсеки</a>', '<a href="?type=PowerBoard">Силовые щиты</a>', '<a href="?type=Engine">Двигатели</a>', ['<a href="?type=PlanetEngine">Планетарные</a>', '<a href="?type=HyperEngine">Межзвездные</a>'], '<a href="?type=Expand">Модули расширения</a>', '<a href="?type=Cargo">Грузовые отсеки</a>', [ '<a href="?type=Container">Контейнеры</a>', '<a href="?type=Hold">Трюмы</a>', '<a href="?type=FuelTank">Цистерны</a>', '<a href="?type=Hangar">Ангары</a>' ]], '<a href="?type=Rocket">Ракеты</a>', '<a href="?type=ShipCase">Корпуса</a>', '<a href="?type=Award">Медали</a>', '<a href="?type=BattleRank">Звания</a>' ]

            template_values = {
#                'url': url,
#                'url_linktext': url_linktext,
                'img_path': 'http://img.starquake.ru',
                'title': 'SQ Primerka',
                'keywords': 'SQ Primerka',
                'description': 'SQ Primerka',
                'url_img': 'http://img.starquake.ru',
                'url_css': 'http://img.starquake.ru/css',
                'moduleTypes': moduletypelist,
                'moduleTypeList': menulist,
                'allowEdit': users.is_current_user_admin(),
                'allowBuy': True,
                }
     
            path = os.path.join(os.path.dirname(__file__), 'templates/list.html')
            data = template.render(path, template_values)
            memcache.set(hashString, data)
            return data


    def get(self):
        if not users.get_current_user():
            self.redirect('/')
            return

        self.response.out.write(self.get_page_data(self.request.get('type'), users.is_current_user_admin(), True, users.is_current_user_admin()))

    def post(self):
        if not users.get_current_user():
            return

        mode = self.request.get('mode')
        key = self.request.get('key')
        action = self.request.get('action')
        if mode=='Edit':
            module = db.get(db.Key(key))

            if action=='Save':
                if int(self.request.get('status')) != module.status:
                    module.status = int(self.request.get('status'))
                    module.put()
            
            if isinstance(module, modules.ModuleType):
                modulelist = [ module ]
            else:
                modulelist = []

            menulist = ['Корабельные модули', ['<a href="?type=Weapon">Оружие</a>', ['<a href="?type=LaserWeapon">Лазерное</a>', '<a href="?type=PlasmaWeapon">Плазменное</a>', '<a href="?type=RocketWeapon">Ракетное</a>', '<a href="?type=MineWeapon">Минное</a>', '<a href="?type=EnergyWeapon">Энергетическое</a>', '<a href="?type=GravityWeapon">Гравитационное</a>'], '<a href="?type=Radar">Радары</a>', ['<a href="?type=BattleRadar">Боевые</a>', '<a href="?type=JammerRadar">Помехи</a>', '<a href="?type=NavigationRadar">Навигационные</a>', '<a href="?type=LongRangeRadar">Сверхдальние</a>'], '<a href="?type=PowerUnit">Энергоустановки</a>', '<a href="?type=Computer">Компьютеры</a>', ['<a href="?type=BattleComputer">Боевые</a>', '<a href="?type=NavigationComputer">Навигационные</a>'], '<a href="?type=Compartment">Жилые отсеки</a>', '<a href="?type=PowerBoard">Силовые щиты</a>', '<a href="?type=Engine">Двигатели</a>', ['<a href="?type=PlanetEngine">Планетарные</a>', '<a href="?type=HyperEngine">Межзвездные</a>'], '<a href="?type=Expand">Модули расширения</a>', '<a href="?type=Cargo">Грузовые отсеки</a>', [ '<a href="?type=Container">Контейнеры</a>', '<a href="?type=Hold">Трюмы</a>', '<a href="?type=FuelTank">Цистерны</a>', '<a href="?type=Hangar">Ангары</a>' ]], '<a href="?type=Rocket">Ракеты</a>', '<a href="?type=ShipCase">Корпуса</a>', '<a href="?type=Award">Медали</a>', '<a href="?type=BattleRank">Звания</a>' ]

            template_values = {
                'img_path': 'http://img.starquake.ru',
                'title': 'SQ Primerka',
                'keywords': 'SQ Primerka',
                'description': 'SQ Primerka',
                'url_img': 'http://img.starquake.ru',
                'url_css': 'http://img.starquake.ru/css',
                'moduleTypes': modulelist,
                'moduleTypeList': menulist,
                'allowEdit': users.is_current_user_admin(),
                'allowBuy': True,
                'modeEdit': True,
                }
    
            path = os.path.join(os.path.dirname(__file__), 'templates/list.html')
            self.response.out.write(template.render(path, template_values))

        elif mode=='Buy':
            module = db.get(db.Key(key))
            if isinstance(module, modules.ModuleType):
                pers = persons.getCurrentPerson()
                modules.buyModule(pers, module)
                self.redirect('/modules?type='+module.__class__.__name__[:-4])
                return
        else:
            self.redirect('/');
    

def main():
    application = webapp.WSGIApplication([('/modules', MainHandler)], debug=True)
    wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
    main()
